import { createBrowserRouter, redirect } from 'react-router-dom';
import About from '../pages/About'
import Home from '../pages/Home'
import NotFount from '../pages/NotFount'
import User from '../pages/User'
import Login from '../pages/Login';
import Goods from '../pages/Goods';

function getData(id:number){
  const userList = [
    {
      id: 1,
      name: '张三',
      age:18
    },
    {
      id: 2,
      name: 'lisi',
      age:19
    },
    {
      id: 3,
      name: 'wangwu',
      age:20
    }
  ]
  return new Promise<{id:number,name:string,age:number}>((resolve) => {
    setTimeout(() => {
      const [user] = userList.filter(item => item.id === id)
      resolve(user)
    }, 1000);
  })
}
async function isLogin({request,params}:any) {
  console.log('isLogin---->');
  // 验证是否有token
  const isAuth = localStorage.getItem('token');
  if(!isAuth){
    console.log('没有token');
    return redirect('/login');
  }
  // 如果是query传参 可以使用request参数获取
  const url = new URL(request.url);
  const id = url.searchParams.get("id"); // /?id=1 
  // 如果是params传参 可以使用params参数获取 xx/:id
  // const id = params.id;
  let userInfo;
  if(id){
    // 获取一些数据
    userInfo=await getData(parseInt(id))
  }else{
    console.log('没有id');
    userInfo = {}
  }
  return userInfo

}
// 既可以作为useRoutes的参数 也可以作为createBrowserRouter
export const routes =[
  {
    path: "/login",
    element: <Login />
  },
  {
    path: "/",
    element: <Home />,
    loader:isLogin,
    children:[
      {
        path: "/about",
        element: <About />
      },
      {
        path: "/user",
        element: <User />
      },
      {
        path: "/goods/:id",
        element: <Goods />
      }
    ]
  },
  {
    path: "*",
    element: <NotFount />
  }
]

// 创建一个历史模式的路由对象
const router = createBrowserRouter(routes);

export default router;